import shutil
from pathlib import Path
from datetime import datetime

class BackupManager:
    def __init__(self, distro_name: str):
        self.backup_dir = Path(f"/var/lib/mirror-tool/backups/{distro_name}")
        self.backup_dir.mkdir(parents=True, exist_ok=True)
    
    def create(self, config_path: Path) -> str:
        """备份配置文件并返回备份路径"""
        timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
        backup_file = self.backup_dir / f"{config_path.name}.{timestamp}"
        shutil.copy(config_path, backup_file)
        return str(backup_file)
    
    def rollback(self, config_path: Path, backup_id: str = "latest"):
        """回滚到指定备份"""
        backups = sorted(self.backup_dir.glob(f"{config_path.name}.*"))
        if not backups:
            raise FileNotFoundError("No backups available")
        
        if backup_id == "latest":
            target = backups[-1]
        else:
            target = self.backup_dir / backup_id
        
        shutil.copy(target, config_path)